//
//  NetworkManager.swift
//  新浪微博
//
//  Created by yaozhen on 2017/12/6.
//  Copyright © 2017年 ZYZ. All rights reserved.
//

import UIKit
import AFNetworking
//swift 的枚举支持任意数据类型
//switch/enum 在OC中都只是支持证书
enum HTTPMethod {
    case GET
    case POST
}

//网络管理工具
class NetworkManager: AFHTTPSessionManager {
    //静态区/常量
    //在第一次访问时 执行闭包 并且将结果保存在shared常量中
    static let shared = { () -> NetworkManager in
       let instance = NetworkManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    lazy var userAcount = UserAcount()
    
    //
    var userLogOn : Bool {
        return userAcount.access_token != nil
    }
    //专门负责拼接 token 的网络请求的方法
    func tokenRequest(method : HTTPMethod = .GET, URLString : String, params : [String : AnyObject]? , completion : @escaping (_ json:AnyObject?,_ isSucces:Bool)->()){
        //调用request 发起真正的网络请求方法
        //处理token字典
        guard let token = userAcount.access_token else {
            //FIXME:发送通知提示用户登录
            print("没有token!需要登录")
            completion(nil,false)
            return
        }
        //1 判断字典为nil 需要重新创建一个字典
        var params = params
        if params == nil {
            params = [String:AnyObject]()
        }
        let token2 = "2.00OtE7AG0A3Fcreb052d04bd0hLnI6" //请求不到 临时新加
        params!["access_token"] = token2 as AnyObject
        request(URLString: URLString, params: params, completion: completion)
    }
    
    
    //使用一个函数封装AFN的GET /POST请求
    
    func request(method : HTTPMethod = .GET, URLString : String, params : [String : AnyObject]? , completion : @escaping (_ json:AnyObject?,_ isSucces:Bool)->()){
        let success = {(task:URLSessionDataTask,json:Any?)->() in

            completion(json as AnyObject,true)
        }
        let failure = { (task : URLSessionDataTask?, error: Error) -> () in
            if (task?.response as?HTTPURLResponse)?.statusCode == 403 {
              print("token过期了")
                
                //FIXME:发送通知（本方法不知道被谁调用，谁接收到通知）
            }
            print("网络错误-------\(error)")
            completion(nil,false)
         }
        if method == .GET {
            get(URLString, parameters: params, progress: nil, success: success, failure: failure)
        }
        else{
            post(URLString, parameters: params, progress: nil, success: success, failure: failure)
        }

        
    }
    
}
